from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.sessions.models import Session

from .models import User
import hashlib

# Create your views here.

def reg_view(request):

    user = None
    if request.method == "GET":
        return render(request, "user/register.html")
    elif request.method == "POST":
        username = request.POST.get('username', None)
        password_1 = request.POST.get('password_1', None)
        password_2 = request.POST.get('password_2', None)
        
        if password_1 != password_2 or len(password_1) < 6:
            return HttpResponse("两次密码不一样，或者密码长度小于6")
        elif 0 == len(username) or len(username)  > 31:
            return HttpResponse("用户名长度错误")
            
        m = hashlib.md5()
        m.update(password_1.encode())
        try:
            user = User.objects.create(username=username, password = m.hexdigest())
        except Exception as err:
            print(f'--create user err:{err}')
            return HttpResponse("用户名已经存在")
    
    request.session['username'] = user.username
    request.session['userid'] = user.id
    
    return HttpResponseRedirect("/index/")
    
def login_view(request):
    
    user = None
    if request.method == "GET":
        # 漏洞
        # print(request.session['username'])
        if request.session.get('username') and request.session.get('userid'):
            return HttpResponseRedirect("/index/")

        return render(request, "user/login.html")
    
    elif request.method == "POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        
        try:
            user = User.objects.get(username=username)
        except Exception as err:
            print(f'--login user err:{err}')
            return HttpResponse('用户名或者密码不匹配')
        m = hashlib.md5()
        m.update(password.encode())
        if user.password == m.hexdigest():
            request.session['username'] = username
            request.session['userid'] = user.id
        else:
            return HttpResponse('用户名或者密码不匹配')
        
        resp = HttpResponseRedirect('/index/')
        if 'remember' in request.POST:
            resp.set_cookie('username', username, 60*60*24*3)
            resp.set_cookie('userid', user.id, 60*60*24*3)
        
        return resp
        
def logout(request):
    
    # 删除session
    if 'username' in request.session:
        del request.session['username']
    if 'userid' in request.session:
        del request.session['userid']
    
    # 删除cookies
    resp = HttpResponseRedirect('/user/login/')
    if 'username' in request.COOKIES:
        resp.delete_cookie('username')
    if 'userid' in request.COOKIES:
        resp.delete_cookie('userid')
    return resp
    